/**
 * @author mashaodong
 * @function 处理音视频所有的回调
 */

import TIM from "tim-js-sdk";
import { getClassChildNode, removeYour } from "./utils";
import { myMessage } from "./error";

export function callableFuns() {
  // 监听客户端房间有人加入
  this.client.on("stream-added", (event) => {
    const yourUserId = event?.stream?.userId_;
    this.yourUserIds.push(yourUserId);
    const remoteStream = event.stream;
    //订阅远端流
    this.client.subscribe(remoteStream);
  });
  // 监听客户端房间有人退出
  this.client.on("stream-removed", (event) => {
    const yourVideoId = document.getElementById("player_" + event.stream.id_);
    const className = yourVideoId.parentElement.getAttribute("class");
    this.yourVideosBox.push(className);
    removeYour("player_" + event.stream.id_);
    const remoteStream = event.stream;
  });
  // 监听客户端房间发生变化
  this.client.on("stream-updated", (event) => {
    const remoteStream = event.stream;
  });
  // 监听远端流订阅成功事件
  this.client.on("stream-subscribed", (evt) => {
    const remoteStream = evt.stream;
    const id = remoteStream.getId();
    const yourVideoId = this.yourVideosBox.shift();
    if (!yourVideoId) {
      myMessage("error", "房间已满");
      return;
    }
    const DomC = getClassChildNode(document, yourVideoId)[0];
    DomC.id = id;
    remoteStream.play(id, { objectFit: "contain" });
  });
}

/**
 * @author mashaodong
 * @function 处理IM所有的回调
 */

export function timCallbackFuns() {
  this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
    const text = JSON.parse(event.data[0].payload.text);
    this.getAccept({
      userName: event.data[0].from,
      message: text.content,
      type: text.type,
    });
  });
}
